package com.example.socketdemo3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author zhanghui
 * @date 2021/12/6 9:57
 */
public class Server {
    public static void main(String[] args) throws IOException {
        int port = 9999;
        // 绑定端口启动服务
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("服务器已启动");
        HandlerSocketThreadPool handlerSocketThreadPool = new HandlerSocketThreadPool(3, 1000);
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("客户端[" + socket.getRemoteSocketAddress() + "]已连接");
            handlerSocketThreadPool.execute(new ReaderClientRunnable(socket));
        }
    }
}

class ReaderClientRunnable implements Runnable {
    private final Socket socket;

    public ReaderClientRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        try {
            inputStream = socket.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String msg = null;
            while ((msg = bufferedReader.readLine()) != null) {
                System.out.println("接收[" + socket.getRemoteSocketAddress() + "]数据: " + msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


